package com.ds.infrastructure.hyperspace.container.internal.opentracing.impl;

import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;

import static com.ds.infrastructure.hyperspace.container.internal.opentracing.impl.TracerConstants.BAGGAGE_KEY_ZIPKIN_SAMPLED;
import static com.ds.infrastructure.hyperspace.container.internal.opentracing.impl.TracerConstants.BAGGAGE_VALUE_SAMPLED;

/**
 * @Author: yaozh
 * @Description:
 */
public class TracerSpan {
    @Getter
    private final String parentId;
    @Getter
    private final String traceId;
    @Getter
    private final String spanId;
    @Getter
    private final long startMillis;
    @Getter
    @Setter
    private String operationName;
    @Getter
    private long finishMillis;
    private boolean finished;
    @Getter
    private final Map<String, Object> tags;
    @Getter
    private final Map<String, String> baggage;

    public TracerSpan(String parentId, String traceId, String spanId, Map<String, String> baggage) {
        this.parentId = parentId;
        this.traceId = traceId;
        this.spanId = spanId;
        this.startMillis = System.currentTimeMillis();
        this.tags = new HashMap<>(20);
        this.baggage = new HashMap<>(baggage);
        this.finished = false;
    }

    public TracerSpan setTag(String key, Object value) {
        tags.put(key, value);
        return this;
    }

    public String getBaggageItem(String key) {
        return baggage.get(key);
    }

    public void setBaggageItem(String key, String value) {
        baggage.put(key, value);
    }

    public boolean isSampled() {
        return BAGGAGE_VALUE_SAMPLED.equals(getBaggageItem(BAGGAGE_KEY_ZIPKIN_SAMPLED));
    }

    public boolean isFinish() {
        return finished;
    }

    public void finish() {
        finishMillis = System.currentTimeMillis();
        finished = true;
    }
}
